<template>
  <div>
    <el-col :span="24" class="bg1">
      <div class="grid-content bg-purple">
        <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :isSubmitBtn="false" />
      </div>
    </el-col>
    <el-col :span="24" class="bg2">
      <BreakSpace label="活动VIN列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FilterTable
        :isExportExcel="false"
        exportFileName="vin数据.xlsx"
        :onCalcExportData="handleExportFun"
        ref="table"
        height="200"
        :onSyncTableData="vinTableChangeFun"
        selectionType="single"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchapiVin"
        :params="fetchParamsVin"
        datakey="records"
        columnsRef="yxqPjxmTable"
        :isColumnFilter="true"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >

      </FilterTable>
    </el-col>

    <el-col :span="24" class="bg2">
      <BreakSpace label="维修工时" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>

      <FilterTable
        ref="tableSport"
        selectionType="single"
        height="200"
        :isSelectColumn="false"
        :columns="columnSport"
        :onSyncTableData="sportTableChangeFun"
        :isMemoryPagination="true"
        columnsRef="yxqPjxmTable"
        :onColumnsChange="columns => (this.columnSport = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
      </FilterTable>
    </el-col>

    <el-col :span="24" class="bg2">
      <BreakSpace label="维修备件" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>

      <FilterTable
        ref="tablePeij"
        height="200"
        :onSyncTableData="peijTableChangeFun"
        :onCellChange="onCellChange"
        :isSelectColumn="false"
        selectionType="single"
        :columns="columnPeij"
        :isMemoryPagination="true"
        columnsRef="yxqPjxmTable"
        :onColumnsChange="columns => (this.columnPeij = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
      </FilterTable>
    </el-col>
    <el-col :span="24" class="bg2">
      <BreakSpace label="附加项目" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>

      <!--   :fetchapi="fetchApiPeij"
        :params="fetchParamPeij"-->
      <FilterTable
        ref="tableFuj"
        height="200"
        :onSyncTableData="fujTableChangeFun"
        :onCellChange="onCellChange"
        :isSelectColumn="false"
        selectionType="single"
        :columns="columnFuj"
        :isMemoryPagination="true"
        columnsRef="yxqFujTable"
        :onColumnsChange="columns => (this.columnFuj = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
      </FilterTable>
    </el-col>

    <div class="dialogBottmView">
      <el-button size="small" type="primary" class="btnStyle" @click="closeMenu('3')">关闭 </el-button>
    </div>
  </div>
</template>

<script>
import { addTtRpMa, getByMaId, getVinByMaId, delMaItem, downVinTem, getAllUser, savePassOrBack, queryUnitCode ,findFileByUrl} from '@/api/repair/batchEventManagement/activityDistribution';

import { exportByMaId } from '@/api/repair/batchEventManagement/activityQueryCDuan';

import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';

import { arrayObjDeWeight } from '@/utils';

import { saveClaimPassOrBack } from '@/api/repair/batchEventManagement/activityClaim';

import { dictionary } from '@/utils/dictMixin';
import { isEmpty } from '@/utils/utils';
import { exportExcelFile } from '@/utils/index';
import { getAppId } from '@/assets/js/auth';
// import { findFileByUrl } from '@/api/partsmanage/financialManagement/capitalAccount/index';
import config from '@/assets/js/config';


export default {
  name: 'detail',
  mixins: [dictionary, dealerMixin],
  /*handleType show   活动审核  show-1  索赔审核*/
  props: ['handleType', 'maId'],
  data() {
    this.saveData = null;
    return {
      uploadPrefix: config.uploadUrl,
      appendixName :'',
      columnSport: this.createTableColumnSport(),
      columnPeij: this.createTableColumnPeij(),
      columnFuj: this.createTableColumnFuj(),
      columnSuopei: this.createTableColumnSuopei(),
      columnDealWay: this.createTableColumnDealWay(),
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      formList2: this.createFormList2(),
      visibleVin: false,
      visibleSport: false,
      visiblePeij: false,
      visibleMainCode: false,
      fetchParams: { xhrAbort: true },
      fetchParamPeij: { xhrAbort: true },
      fetchParamSport: { xhrAbort: true },
      fetchParamSuopei: { xhrAbort: true },
      fetchApiPeij: '',
      fetchApi: '',
      fetchApiSport: '',
      fetchApiSuopei: '',
      fetchapiVin: getVinByMaId,
      fetchParamsVin: { xhrAbort: true },
      onChangeColumn: [],
      vinArr: [] /**/,
      sportArr: [],
      peijArr: [],
      fujArr:[],
      status: 1 /*1  表单选择  2 新建配件*/,
      detailObj: {},
      imageList: [],
      UploadFileIsShow: false,
      // actionUrl: '/api/dmscloud.activity/ttRpMa/uploadVinTem'//本地
      actionUrl: 'https://dcs-test-api.livanauto.com/api/dmscloud.activity/ttRpMa/uploadVinTem',//测试环境

    };
  },
  components: {},
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.BaseSportTable = this.$refs.tableSport.$refs.pageTable;
    this.BasePeijTable = this.$refs.tablePeij.$refs.pageTable;
    this.BaseFujTable = this.$refs.tableFuj.$refs.pageTable;

    // this.BaseSuopeiTable = this.$refs.tableSuopei.$refs.pageTable;

    // this.getAllDelears(this.columns, ['resDealer', 'updateCode', 'salesDealer'], 'table');

    this.getData();

    this.initSelect();

    this.getUnit();
  },
  methods: {
    async exportHandle() {
      let params = {
        maId: this.maId
      };
      await this.downHandleFile(exportByMaId, params, 'vin数据');
    },
    cheageselect(data){
          console.log(data)
        this.txt.data

    },
    async getUnit() {
    },

      //获取附件url
    async getPicUrl(url) {
      let actionUrl = 'https://dcs-test-api.livanauto.com/api/file/download/url?fileUrl=' + url;
      let res = await axios.post(actionUrl);
      return res.data;
    },

    async initSelect() {
      this.getAllUsers(this.columnSuopei, ['createdBy'], 'table');
    },

    handleExportFun(row) {
      row.vinStatus = this.createDictText(row.vinStatus, 6040);

      let oldResDealer = isEmpty(row['oldResDealer']) ? '' : row['oldResDealer'];
      let oldVinStatus = isEmpty(row['oldVinStatus']) ? '' : row['oldVinStatus'];

      let status = '';

      if (isEmpty(oldResDealer) && isEmpty(oldVinStatus)) {
        status = '否';
      } else {
        status = '是';
      }
      row.status = status;

      row.vinStatus = this.createDictText(row.vinStatus, 4021);
    },

    /*配置数量发生改变的时候执行*/
    onCellChange(e, obj) {
      let counts = isEmpty(obj['counts']) ? '0' : obj['counts'];
      let price = isEmpty(obj['price']) ? '0' : obj['price'];
      let amount = obj['amount'];

      let toatalCount = isEmpty(parseInt(counts) * parseInt(price)) ? '0' : parseInt(counts) * parseInt(price);

      obj['amount'] = toatalCount;

      this.BasePeijTable.DO_REFRESH(false);
    },

    /*导入*/
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
    },


    successHandler(e) {
      console.log('e:::', e);
      if (e != 1) {
        let obj = e[e.length - 1];
        let data = obj['url'];
        let error = data['error'];
        let successArr = data['success'];

        let newArr = [];
        console.log('successArr--', successArr);
        successArr.forEach((item, index) => {
          if (this.vinArr.length > 0) {
            this.vinArr.forEach((obj, pos) => {
              if (item['vin'] != obj['vin']) {
                newArr.push(item);
              }
            });
          } else {
            newArr.push(item);
          }
        });

        if (!isEmpty(error)) {
          this.$notify.error({ title: '提示信息', message: '导入失败数据为:' + error });
        }

        this.BaseTable.EXECUTE_INSERT(newArr);
      }
      this.UploadFileIsShow = false;
    },

    /*根据ID查询*/
    async getData() {
      let res = await getByMaId({ maId: this.maId });
      this.fetchParamsVin = Object.assign({}, this.fetchParamsVin, { maId: this.maId, xhrAbort: false });
      if (res.resultCode == 200 && res.success == true) {
        let data = isEmpty(res['data']) ? {} : res['data'];
        // let ttRpMaAreas = data['ttRpMaAreas'];
        let ttRpMaLabours = data['ttRpMaLabours'];
        let ttRpMaParts = data['ttRpMaParts'];
        // let ttRpMaLogVOS = data['ttRpMaLogVOS'];
        let ttRpMaAddVOS = data['ttRpMaAddVOS'];


        // this.BaseTable.EXECUTE_INSERT(ttRpMaAreas);
        this.BaseSportTable.EXECUTE_INSERT(ttRpMaLabours);
        this.BasePeijTable.EXECUTE_INSERT(ttRpMaParts);
        // this.BaseSuopeiTable.EXECUTE_INSERT(ttRpMaLogVOS);
         this.BaseFujTable.EXECUTE_INSERT(ttRpMaAddVOS);
         this.appendixName = data.appendixName;


        for (let i in data) {
          this.formList.map(x => {


            if (i == x.fieldName) {
              x.initialValue = x.fieldName === 'maStrategy'? Number(data[i]):data[i];//mo

            }
          });
        }


         this.appendixName = data.appendixName ? JSON.parse(data.appendixName) : [];
        this.appendixAddress = data.appendixAddress ? JSON.parse(data.appendixAddress) : [];


        // 数据组装
        const files = [];
        if (this.appendixName) {
          this.appendixName.forEach((name, index) => {
            //  findFileByUrl(this.appendixAddress[index]).then(res => {
            //   this.imageList.push({name: name,url: res.data});
            // });
           files.push({
              name,
              url: this.appendixAddress[index],
            });
          });

          // this.formList.find(item => item.fieldName === 'appendixAddress').initialValue = this.imageList;
          // 数据赋值
          this.formList.find((x) => {
            x.fieldName === 'appendixAddress' && (x.initialValue = files);
          });
        }

      }
    },

    peijTableChangeFun(val) {
      this.peijArr = val;
    },
    fujTableChangeFun(val) {
      this.fujArr = val;
    },

    vinTableChangeFun(val) {
      this.vinArr = val;

      val.forEach((item, index) => {
        let oldResDealer = isEmpty(item['oldResDealer']) ? '' : item['oldResDealer'];
        let oldVinStatus = isEmpty(item['oldVinStatus']) ? '' : item['oldVinStatus'];
        let status = '';
        if (isEmpty(oldResDealer) && isEmpty(oldVinStatus)) {
          status = '否';
        } else {
          status = '是';
        }
        item.status = status;
      });
    },

    sportTableChangeFun(val) {
      this.sportArr = val;
    },

    async closeMenu(type) {
      this.$emit('close');
    },
    closeDialog() {
      this.visibleVin = false;
      this.visibleSport = false;
      this.visiblePeij = false;
    },
    createTableColumnDealWay() {
      return [
        {
          type: 'INPUT',
          label: '结算金额',
          fieldName: 'settlementAmount',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '原因分析',
          fieldName: 'causeAnalysis',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '措施制定',
          fieldName: 'maStrategy',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '市场车辆实施措施',
          fieldName: 'marketMeasures',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '销售配件实施措施',
          fieldName: 'partMeasures',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'BREAK_SPACE',
          label: 'fqms附件信息'
        },
        {
          type: 'INPUT',
          label: '批量报告附件名称',
          fieldName: 'appendixName',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'UPLOAD_FILE',
          label: '批量报告附件地址',
          fieldName: 'appendixAddress',
          placeholder: '请选择',
          disabled: true,
          selfCols: 2,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '作业指导书名称',
          fieldName: 'guidanceName',
          placeholder: '请选择',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'UPLOAD_FILE',
          label: '作业指导书地址',
          fieldName: 'guidnaceAddress',
          placeholder: '请选择',
          selfCols: 2,
          disabled: true,
          initialValue: ''
        }
      ];
    },
    createFormList() {

      return [
        {
          type: 'BREAK_SPACE',
          label: '批量活动基本信息'
        },

        {
          type: 'INPUT',
          label: '活动编号：',
          fieldName: 'maNo',
          itemList: [],
          disabled: true,
          placeholder: '',
          // rules: [{required: true, trigger: 'change'}],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '活动名称：',
          fieldName: 'maTitle',
          disabled: true,
          rules: [{ required: false, trigger: 'change' }],
          placeholder: '请输入',
          initialValue: ''
        },

        {
          type: 'DATE',
          label: '活动开始日期：',
          fieldName: 'bDate',
          disabled: true,
          format: 'yyyy-MM-dd',
          placeholder: '请选择',
          rules: [{ required: false, trigger: 'change' }],
          initialValue: ''
        },

        {
          type: 'DATE',
          label: '活动截止日期：',
          fieldName: 'eDate',
          disabled: true,
          format: 'yyyy-MM-dd',
          placeholder: '请选择',
          rules: [{ required: false, trigger: 'change' }],
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '活动类型：',
          fieldName: 'maStrategy',
          placeholder: '请选择',
          disabled: true,
          // rules: [{ required: true, message: '请选择',trigger: 'change'}],
          itemList: this.createDictList('5080'),
          initialValue: ''

        },

        {
          type: 'TEXT_AREA',
          label: '活动说明',
          fieldName: 'maRemarks',
          placeholder: '请选择',
          disabled: true,
          rules: [{ required: false, trigger: 'change' }],
          initialValue: '',
          selfCols: 3
        },

        {
          type: 'UPLOAD_FILE',
          label: '附件',
          disabled: true,
          fieldName: 'appendixAddress',
          disabled: true,
          initialValue: '',
          selfCols: 4,
          // upload: {
          //   // actionUrl: '/api/file/oss/upload'//本地
          //   actionUrl: 'https://dcs-test-api.livanauto.com/api/file/oss/upload' //测试

          // }
        }

      ];
    },
    createFormList2() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '审核说明'
        },
        {
          type: 'TEXT_AREA',
          label: '审核说明',
          fieldName: 'checkRemarks',
          placeholder: '请选择',
          disabled: false,
          rules: [{ required: false, trigger: 'change' }],
          initialValue: '',
          selfCols: 3
        }
      ];
    },
    /*索赔*/
    createTableColumnSuopei() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '操作时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '操作后状态',
          dataIndex: 'checkStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1022),
          render: props => {
            console.log(props.row.checkStatus);
            return <span>{this.createDictText(props.row.checkStatus, 1022)}</span>;
          }
        },
        {
          title: '审核说明',
          dataIndex: 'checkRemarks',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },

    /*配件*/
    createTableColumnPeij() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '备件代码',
          dataIndex: 'partCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
        },
        {
          title: '数量',
          dataIndex: 'counts',
          sorter: true,
          filter: true,
          filterType: 'input',
          editType: 'number',
          editable: false
        },
        {
          title: '账类',
          dataIndex: 'costType',
          disabled: true,
          itemList: this.createDictList(5803),
          filterItems: this.createDictList('5803'),
          render: props => {
            return <span>{this.createDictText(props.row.costType, '5803')}</span>;
          }
        },

          {
          title: '关联维修工时',
          dataIndex: 'mlId',
          sorter: true,
          editType: 'select',
          editItems: this.sportArr,
          editable: true,  //mark
          disabled:true,
          render: props => {
            let targetname = '';
            const {sportArr} = this;
            sportArr.forEach(item=>{
             if(props.row.mlId == item.labourId){
               targetname = item.labourName
             }
            })
            return targetname

          }
        },

      ];
    },

    /*活动*/
    createTableColumnSport() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '活动项目代码',
          dataIndex: 'labourCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '活动项目名称',
          dataIndex: 'labourName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '项目类型',
        //   dataIndex: 'labourType',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '标准工时',
          dataIndex: 'stdLabourHour',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
 {
          title: '账类',
          dataIndex: 'costType',
          disabled: true,
          itemList: this.createDictList(5803),
          filterItems: this.createDictList('5803'),
          render: props => {
            return <span>{this.createDictText(props.row.costType, '5803')}</span>;
          }
        },
      ];
    },
     //附加项目
    createTableColumnFuj() {
      return [
         {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },

        {
          title: '项目代码',
          dataIndex: 'itemCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '项目名称',
          dataIndex: 'itemName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '项目费用',
          dataIndex: 'itemPrice',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterType: 'input'

        },

       {
          title: '账类',
          dataIndex: 'costType',
          disabled: true,
          itemList: this.createDictList(5803),
          filterItems: this.createDictList('5803'),
          render: props => {
            return <span>{this.createDictText(props.row.costType, '5803')}</span>;
          }
        },
        {
          title: '项目说明',
          dataIndex: 'itemRemark',
          sorter: true,
          filter: true,
          filterType: 'input'
        }


      ];

    },
    //VIN列表
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          // width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '责任站代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false

        },
        {
          title: '责任站简称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'

        }
      ];
    }
  }
};
</script>

<style scoped lang="less">
.bg1 {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  padding-left: 0;
  padding-top: 15px;
  padding-bottom: 15px;
}

.bg2 {
  margin-top: 10px;
  margin-bottom: 10px;
}

.btn {
  text-align: center;
}

.btnStyle {
  margin-top: 10px;
}
</style>
